<script setup>
  import { ref } from 'vue'
  import { storeToRefs } from 'pinia'

  import FormFlatLayout from '@/layouts/FormFlatLayout.vue'

  import { useCompanyConfigStore, useCompanyStore } from '@/stores/company'

  import CompanyForm from '@/components/company/CompanyForm.vue'

  const props = defineProps({
    edit: { type: Boolean, default: false },
    companyId: { type: Number || null, default: null },
    url: { type: String, required: true },
    formConfigUrl: { type: String, required: true },
    layout: { type: Object, default: FormFlatLayout },
  })

  const emit = defineEmits(['saved', 'cancel'])

  const loading = ref(true)

  const formConfigStore = useCompanyConfigStore()
  formConfigStore.setUrl(props.formConfigUrl)
  const isEdit = !!props.companyId
  const companyStore = useCompanyStore()

  async function preload() {
    const promises = [formConfigStore.loadConfig()]

    if (isEdit) {
      companyStore.setCurrentCompanyId(props.companyId)
      promises.push(companyStore.loadCompany(props.companyId))
    }
    Promise.all(promises).then(() => (loading.value = false))
  }

  const { item: company } = storeToRefs(companyStore)

  function onSaved(item) {
    console.log('Company saved')
    emit('saved', item)
  }

  await preload()
</script>

<template>
  <div v-if="loading">Chargement…</div>
  <CompanyForm
    v-else
    :company="company || {}"
    @saved="onSaved"
    @cancel="emit('cancel')"
    :layout="layout"
  />
</template>
